package com.yserp.project.erp.bill.receivemoney.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yserp.common.exception.BusinessException;
import com.yserp.common.utils.StringUtils;
import com.yserp.common.utils.bean.BeanUtils;
import com.yserp.common.utils.mybatis.MybatisPlusUtil;
import com.yserp.common.utils.text.Convert;
import com.yserp.project.erp.bill.receivemoney.domain.ReceiveMoney;
import com.yserp.project.erp.bill.receivemoney.domain.ReceiveMoneyDto;
import com.yserp.project.erp.bill.receivemoney.domain.ReceiveMoneyItem;
import com.yserp.project.erp.bill.receivemoney.domain.ReceiveMoneyVo;
import com.yserp.project.erp.bill.receivemoney.mapper.ReceiveMoneyMapper;
import com.yserp.project.erp.bill.receivemoney.service.IReceiveMoneyItemService;
import com.yserp.project.erp.bill.receivemoney.service.IReceiveMoneyService;
import com.yserp.project.erp.common.enums.CheckStatusEnums;
import com.yserp.project.erp.common.enums.OrderEnums;
import com.yserp.project.erp.common.enums.ReceiveMoneyStatusEnums;
import com.yserp.project.erp.common.util.DateSearchUtils;
import com.yserp.project.erp.order.saleorder.domain.ErpSaleOrder;
import com.yserp.project.erp.order.saleorder.service.IErpSaleOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 收款单Service业务层处理
 *
 * @author yserp
 * @date 2022-08-11
 */
@Service
public class ReceiveMoneyServiceImpl extends ServiceImpl<ReceiveMoneyMapper, ReceiveMoney> implements IReceiveMoneyService {
    @Resource
    private ReceiveMoneyMapper receiveMoneyMapper;
    @Autowired
    private IReceiveMoneyItemService receiveMoneyItemService;
    @Autowired
    private IErpSaleOrderService erpSaleOrderService;

    /**
     * 查询收款单
     *
     * @param id 收款单主键
     * @return 收款单
     */
    @Override
    public ReceiveMoneyVo selectReceiveMoneyById(Long id) {
        return ReceiveMoneyVo.builder()
                .receiveMoney(receiveMoneyMapper.selectById(id))
                .items(receiveMoneyItemService.selectReceiveMoneyItemListByMainId(id))
                .build();
    }

    /**
     * 查询收款单列表
     *
     * @param receiveMoney 收款单
     * @return 收款单
     */
    @Override
    public List<ReceiveMoney> selectReceiveMoneyList(ReceiveMoney receiveMoney) {
        QueryWrapper<ReceiveMoney> queryWrapper = new QueryWrapper<>();
        MybatisPlusUtil.notNullField(receiveMoney, queryWrapper);
        //对时间区间的处理
        DateSearchUtils.queryDateRange(receiveMoney,queryWrapper);
        return receiveMoneyMapper.selectList(queryWrapper);
    }

    /**
     * 新增收款单
     *
     * @param receiveMoneyDto 收款单
     * @return 结果
     */
    @Override
    @Transactional
    public int insertReceiveMoney(ReceiveMoneyDto receiveMoneyDto) {
        List<ReceiveMoneyItem> items = receiveMoneyDto.getItems();
        if (CollectionUtils.isEmpty(items)) {
            throw new BusinessException("子表不能为空");
        }
        //验证单号是否存在
        String orderNo = receiveMoneyDto.getOrderCode();
        if(StringUtils.isBlank(orderNo)){
            throw new BusinessException("单号不存在");
        }
        Integer count = receiveMoneyMapper.selectCount(new QueryWrapper<ReceiveMoney>().eq("order_code", orderNo));
        if(count>0){
            throw new BusinessException("单号已存在，请重新下单");
        }else{
            OrderEnums.putCacheOrderNo(orderNo);
        }
        //插入主表
        ReceiveMoney receiveMoney = new ReceiveMoney();
        BeanUtils.copyBeanProp(receiveMoney, receiveMoneyDto);
        int i = receiveMoneyMapper.insert(receiveMoney);
        //批量插入子表
        items.stream().forEach(item -> item.setMainId(receiveMoney.getId()));
        receiveMoneyItemService.saveBatch(items);
        return i;
    }

    /**
     * 修改收款单
     *
     * @param receiveMoneyDto 收款单
     * @return 结果
     */
    @Override
    @Transactional
    public int updateReceiveMoney(ReceiveMoneyDto receiveMoneyDto) {
        List<ReceiveMoneyItem> items = receiveMoneyDto.getItems();
        if (CollectionUtils.isEmpty(items)) {
            throw new BusinessException("子表不能为空");
        }
        //修改主表(运用了乐观锁)
        ReceiveMoney receiveMoney = receiveMoneyMapper.selectById(receiveMoneyDto.getId());
        BeanUtils.copyBeanProp(receiveMoney, receiveMoneyDto);
        int i = receiveMoneyMapper.updateById(receiveMoney);
        //子表
        Long mainId = receiveMoney.getId();
        //获取子表
        List<ReceiveMoneyItem> receiveMoneyItems = receiveMoneyItemService.selectReceiveMoneyItemListByMainId(mainId);
        if (!CollectionUtils.isEmpty(receiveMoneyItems)) {
            List<Long> oldIds = receiveMoneyItems.stream().map(ReceiveMoneyItem::getId).collect(Collectors.toList());
            List<Long> newIds = items.stream().map(ReceiveMoneyItem::getId).collect(Collectors.toList());
            oldIds.removeAll(newIds);
            if (!CollectionUtils.isEmpty(oldIds)) {
                receiveMoneyItemService.removeByIds(oldIds);
            }
        }
        for (ReceiveMoneyItem item : items) {
            item.setMainId(mainId);
            receiveMoneyItemService.saveOrUpdate(item);
        }
        return i;
    }

    /**
     * 批量删除收款单
     *
     * @param ids 需要删除的收款单主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteReceiveMoneyByIds(String ids) {
        int result = 0;
        Long[] mainIds = Convert.toLongArray(ids);
        for (Long id : mainIds) {
            result = this.deleteReceiveMoneyById(id);
            if (result <= 0) {
                break;
            }
        }
        return result;
    }

    /**
     * 删除收款单信息
     *
     * @param id 收款单主键
     * @return 结果
     */
    @Override
    public int deleteReceiveMoneyById(Long id) {
        int result = 0;
        //更新主表
        int i = receiveMoneyMapper.deleteById(id);
        //查询子表信息
        List<ReceiveMoneyItem> items = receiveMoneyItemService.selectReceiveMoneyItemListByMainId(id);
        if (!CollectionUtils.isEmpty(items)) {
            List<Long> itemIds = items.stream().map(ReceiveMoneyItem::getId).collect(Collectors.toList());
            boolean b = receiveMoneyItemService.removeByIds(itemIds);
            if (i > 0 && b) {
                result = 1;
            }
        }
        return result;
    }

    @Override
    @Transactional
    public int auditReceiveMoneyByIds(String ids) {

        ReceiveMoney receiveMoney = null;
        Long[] mainIds = Convert.toLongArray(ids);
        for (Long id : mainIds) {
            receiveMoney = receiveMoneyMapper.selectById(id);
            //如果已审核，无须再次审核
            if(CheckStatusEnums.OK_CHECK.getCode().equals(receiveMoney.getOrderStatus())){
                continue;
            }
            //1.更新状态
            receiveMoney.setOrderStatus(CheckStatusEnums.OK_CHECK.getCode());
            receiveMoneyMapper.updateById(receiveMoney);
            //2.同步采购单数据
            List<ReceiveMoneyItem> items = receiveMoneyItemService.selectReceiveMoneyItemListByMainId(id);
            for (ReceiveMoneyItem item : items) {
                ErpSaleOrder order = erpSaleOrderService.getById(item.getSaleId());
                //付款状态
                BigDecimal receiveAmount = item.getReceiveAmount();
                BigDecimal noReceiveAmount = item.getNoReceiveAmount();
                if (noReceiveAmount.compareTo(receiveAmount)==0) {
                    order.setReceiveStatus(ReceiveMoneyStatusEnums.OK_RECEIVE_MONEY.getCode());
                }else{
                    order.setReceiveStatus(ReceiveMoneyStatusEnums.PART_RECEIVE_MONEY.getCode());
                }
                //收款金额
                BigDecimal receiveAmounts = order.getReceiveAmount();
                receiveAmounts = receiveAmounts.add(receiveAmount);
                order.setReceiveAmount(receiveAmounts);
                erpSaleOrderService.updateById(order);
            }
        }

        return 1;
    }
}
